<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use think\facade\Cache;
use think\facade\View;
use think\Request;

class Type extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return View::fetch();
    }

    public function types(Request $request)
    {
        $limit = input('limit');
        $key = input('key');
        if ($key == '') {
            $data = \app\admin\model\Type::paginate($limit)->toArray();
        } else {
            $data = \app\admin\model\Type::where('tname', "$key")->paginate($limit)->toArray();
        }
        return json(['code' => 0, 'count' => $data['total'], 'data' => $data['data']]);
    }

    public function redis()
    {
        $reids = Cache::store('redis');
        $data = \app\admin\model\Type::select();
        $data && $data->toArray();
        $flag = $reids->set('type', json_encode($data));
        if ($flag) {
            return json(['code' => 200, 'data' => '', 'msg' => '缓存成功']);
        } else {
            return json(['code' => 300, 'data' => '', 'msg' => '缓存失败']);
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return View::fetch();
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $params = $request->param();
        try {
            $this->validate($params, [
                'tname' => 'require'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 300, 'msg' => '分类名称不能为空', 'data' => '']);
        }
        $params['add_time'] = time();
        $flag = \app\admin\model\Type::create($params);
        if ($flag) {
            return json(['code' => 200, 'msg' => '添加成功', 'data' => '']);
        } else {
            return json(['code' => 300, 'msg' => '添加失败', 'data' => '']);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {
        $id = $request->get('id');
        $flag = \app\admin\model\Type::destroy($id);
        if ($flag) {
            return json(['code' => 200, 'msg' => '删除成功', 'data' => '']);
        } else {
            return json(['code' => 300, 'msg' => '删除失败', 'data' => '']);
        }
    }
}
